/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package request.location;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "request_location")
@RequestScoped
public class Main extends Beans {
    //Variables de importación General

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    //Variables de importación otros modulos
    //Variables del modulo
    private Find request_locationFind = new Find();
    private request.general.Find request_generalFind = new request.general.Find();
    private List<Beans> request_generalList = new ArrayList<>();
    private List<request.general.Beans> solicitudgeneralList = new ArrayList<>();
    //Variables locales
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();

    public Main() throws Exc, SQLException, Exception {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
        load();
    }

    private void load() {
        try {

            //Verifica si hay un registro seleccionado
            if (logged.getMasterId() == 0) {
                return;
            }

            map.clear();
            map.put("s.id = " + logged.getMasterId(), " ");

            request_generalList.clear();
            solicitudgeneralList = request_generalFind.byMap(map);
            getUniversityBeans().setId(solicitudgeneralList.get(0).getUniversityBeans().getId());

            if (logged.getDetailId() == 0) {
                return;
            }
            map.clear();
            request_generalList.clear();
            map.put("css.id_solicitud= " + logged.getMasterId(), " ");
            request_generalList = request_locationFind.byMap(map);
            setId(request_generalList.get(0).getId());
            setId_solicitud(request_generalList.get(0).getId_solicitud());
            setId_sede(request_generalList.get(0).getId_sede());

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {
            if (logged.getMasterId() == 0 || getId_sede() == 0) {
                throw new Exc("m4");
            }
            if (getId_sede() == 0) {
                throw new Exc("m22");
            }

            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("css.id_solicitud= " + logged.getMasterId(), " AND ");
            map.put("css.id_sede = " + getId_sede(), " ");

            if (request_locationFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "INSERT INTO public.solicitud_sede (id_solicitud,id_sede) "
                    + "VALUES (" + logged.getMasterId() + ", " + getId_sede() + ")";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            request_generalList = request_locationFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setDetailId(request_generalList.get(0).getId());
            setId(logged.getDetailId());

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {

            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }

            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("css.id <> " + logged.getDetailId(), " AND ");
            map.put("css.id_solicitud= " + getId_solicitud(), " AND ");
            map.put("css.id_sede = " + getId_sede(), "  ");

            if (request_locationFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "UPDATE public.solicitud_sede SET "
                    + "id_sede = " + getId_sede() + " "
                    + "WHERE id =" + logged.getDetailId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getDetailId());

            logged.setDetailId(0);
            clearBeans();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        //Elimina el Usuario por id
        sql = "DELETE FROM public.solicitud_sede "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void insertUniversity() throws Exc, SQLException, Exception {
        university.general.Main universidad = new university.general.Main();
        getUniversityBeans().setId(universidad.insert(getUniversityBeans().getNombre(), getUniversityBeans().getFundada(), getUniversityBeans().getDetalle()));
        getUniversityBeans().setNombre("");
        getUniversityBeans().setFundada(0);
        getUniversityBeans().setDetalle("");
    }

    public void clear() {
        clearBeans();
        getUniversityBeans().clearBeans();
        getFacultyBeans().clearBeans();
        logged.setDetailId(0);
        logged.setMasterId(0);
    }

    public void selectedLocation(ValueChangeEvent event) throws Exc, SQLException, Exception {
        setId_sede(Integer.parseInt(event.getNewValue().toString()));
    }

    public void selectedFaculty(ValueChangeEvent event) throws Exc, SQLException, Exception {
        logged.setDetailId(0);
        setId(0);
        logged.setMasterId(Integer.parseInt(event.getNewValue().toString()));
    }

    public void selectedTempId(int recordId) {
        logged.setDetailId(recordId);
        load();
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
